package com.shcowin.filter;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class LoginFilter extends HttpServlet implements Filter {

	private static final long serialVersionUID = 1L;
	private FilterConfig filterConfig;

	public void destroy() {
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		this.filterConfig = filterConfig;
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		String currentURL = req.getRequestURI();
		String targetURL = currentURL.substring(currentURL.indexOf("/", 1));

		currentURL.length();
		HttpSession session = req.getSession();

		// 判断是不是请求登陆页面，如果是则放过
		if(targetURL.lastIndexOf(".html") != -1 || targetURL.lastIndexOf(".do") != -1){
			if ("/admin/login.html".indexOf(targetURL)==-1 && "/admin/login.do".indexOf(targetURL)== -1 && "/admin/illegalVisit.html".indexOf(targetURL) == -1) {
				if (session == null || session.getAttribute("username") == null) {
					res.sendRedirect(req.getContextPath() + "/admin/illegalVisit.html");
					return;
				}
			}
		}
		chain.doFilter(req, res);
	}
}